import React, { useState, useEffect, useLayoutEffect  } from 'react';
import {Input, Select, Form, Box, Button, Card, DatePicker, Message, Radio, Upload, Switch, Dialog } from '@alifd/next';
import BasicForm from '@/pages/FormBasic/components/BasicForm';
import styles from './index.module.scss';
import {detail, update} from '@/api/UserAPI'
import {upLoadImage} from '@/api/CommonAPI'
const FormItem = Form.Item;
const formItemLayout = {
  colSpan: 6,
};
let times = 0;

const DEFAULT_DATA = {
    userType: '0',
    sex: '1',
    loginName:'',
    password:'',
    phoneNum:'',
    name:'',
    code:'',
    nickName:'',
    logoUrl:'',
    email:'',
  };

const UpdateUser = props => {
    // 修改表单部分
    const { dataSourceUpdate = DEFAULT_DATA} = props;
    const [postData, setPostData] = useState(dataSourceUpdate);
    // Dialog 弹框部分
    console.log('初  props::', props)
    const [loading, setLoading] = useState(false);
    const [short, setShort] = useState(false);
    const [shouldUpdatePosition, setShouldUpdatePosition] = useState(true);
    const [sexUpdateValue, setUpdateSex] = useState(null);
    const [imageData, setImageData] = useState([]);
    const [sourceFlag, setSourceFlag] = useState(false);
    const id = props.userId;
    useEffect (() => {
        console.log('标识：：：loadDataFlag：', times)
        props.onRef;
        // openModifyComponent(id)
        // setLoading(true)
    },[]);
    // 1 打开弹框
    const openModifyComponent =(id) => {
        console.log('初  openModifyComponent')
        if(!id){
            return;
        }
        setImageData([])
        // 查询单条信息
        detail(id).then((data)=>{
          if(data){
            console.log('详情数据：：：', data)
            // 解析数据复制
            dataSourceUpdate.id = data.id,
            dataSourceUpdate.userType = String(data.userType),
            dataSourceUpdate.sex = String(data.sex),
            dataSourceUpdate.loginName = data.loginName,
            dataSourceUpdate.password = data.password,
            dataSourceUpdate.phoneNum = data.phoneNum,
            dataSourceUpdate.name = data.name,
            dataSourceUpdate.code = data.code,
            dataSourceUpdate.nickName = data.nickName,
            dataSourceUpdate.logoUrl = data.logoUrl,
            dataSourceUpdate.logoUrlId = data.logoUrlId,
            imageData.push({
              uid: data.logoUrlId,
              state: 'done',
              url: data.logoUrl,
            });
            setImageData(imageData)
            setPostData(dataSourceUpdate)
          }
        });
    };
    // 2 关闭弹框
    const onOpen = (v) => {
        setLoading(true)
    };
    // 2 关闭弹框
    const onClose = () => {
        setLoading(false)
    };
    // 3 更新位置
    const toggleShouldUpdatePosition = () => {
        setShouldUpdatePosition(shouldUpdatePosition)
    };
    
    const DEFAULT_ON_SUBMIT = (values, errors) => {
      if (errors) {
        console.log('errors', errors);
        return;
      }
    
      console.log('values:', values);
      Message.success('提交成功');
    };

  const formChange = values => {
    setPostData(values);
  };
  const onCancel = () => {
      onClose();
  };
  // 上传附件
  const upLoadImageBegin = (info) => {
    // 调用上传API
    upLoadImage( 'file', info.file).then((data)=>{
      console.log('上传成功返回数据*****', data)
      // 赋值URL和ID
      dataSourceUpdate.logoUrl = data.url
      dataSourceUpdate.logoUrlId = data.id
      // 回显信息
      let onSuccessInfo = {
        success: true,
        url: data.url,
        uid: data.id,
      }
      info.onSuccess(onSuccessInfo);
    });
  };

  // 提交表单信息
  const onSubmitUpdate = (values, errors) => {
      if (errors) {
        console.log('errors', errors);
        return;
      }
      // 处理上传文件属性
      delete values.file
      values.logoUrl= dataSourceUpdate.logoUrl;
      values.logoUrlId = dataSourceUpdate.logoUrlId
      // 调用新增用户API接口
      update(values).then((flag)=>{
          if(flag){
              Message.success('修改成功');
              setPostData({}); // 清空表单源数据
              setImageData([])
              onClose();
              setLoading(true);
          }
      });
  };
    return (
        <div> 
            <Button type="primary" text onClick={()=>onOpen(model.id)}>编辑</Button>
            <Dialog title="修改用户信息" visible={loading} footer ={false} onClose={onClose}>
                <Card free className={styles.TwoColumnForm}>
                <Card.Content>

                    <Form responsive fullWidth value={postData} labelAlign="top" onChange={formChange}>
                        <FormItem {...formItemLayout} label="ID" required requiredMessage="必填" hidden>
                                <Input name="id" disabled/>
                        </FormItem>
                        <FormItem {...formItemLayout} label="账户登录名：" required requiredMessage="必填">
                            <Input placeholder="请输入用户登录名" name="loginName" />
                        </FormItem>
                        <FormItem {...formItemLayout} label="用户类型：">
                            <Radio.Group name="userType" aria-labelledby="用户类型~">
                                <Radio id="ordinary" value="0">普通用户</Radio>
                                <Radio id="manger" value="1">管理用户</Radio>
                                <Radio id="system" value="-1">系统用户</Radio>
                            </Radio.Group>
                        </FormItem>
                        <FormItem {...formItemLayout} label="账户密码：" required requiredMessage="必填">
                            <Input value="*******" name="password" disabled/>
                        </FormItem>

                        <FormItem {...formItemLayout} label="用户手机号：" required requiredMessage="必填">
                            <Input placeholder="请输入用户手机号" name="phoneNum" />
                        </FormItem>

                        <FormItem {...formItemLayout} label="用户姓名：" required requiredMessage="必填">
                            <Input placeholder="请输入用户姓名" name="name" />
                        </FormItem>
                        <FormItem {...formItemLayout} label="用户代码：" required requiredMessage="必填">
                            <Input placeholder="请输入用户代码" name="code" />
                        </FormItem>
                        <FormItem {...formItemLayout} label="用户昵称：" required requiredMessage="必填">
                            <Input placeholder="请输入用户昵称" name="nickName" />
                        </FormItem>

                        <FormItem {...formItemLayout} label="用户性别：" required requiredMessage="必填">
                            <Radio.Group name="sex" aria-labelledby="用户性别~">
                                <Radio id="man" value='1'>男</Radio>
                                <Radio id="woman" value='2'>女</Radio>
                            </Radio.Group>
                        </FormItem>

                        <FormItem {...formItemLayout} label="上传用户头像：" >
                            <Upload listType="image"
                            accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp" shape="card" 
                            name="file" 
                            limit={1}
                            request={upLoadImageBegin} 
                            defaultValue={imageData}
                            >
                            </Upload>
                        </FormItem>
                        <FormItem {...formItemLayout} label="邮件：" required requiredMessage="必填">
                            <Input placeholder="请输入用户邮件" name="email" />
                        </FormItem>
                        <FormItem colSpan={12} style={{marginLeft:'35%'}}>
                            <Box spacing={8} direction="row" align="center">
                                <Form.Submit type="primary" onClick={onSubmitUpdate} validate>提交</Form.Submit>
                                <Button onClick={onCancel} type="secondary">取消</Button>
                            </Box>
                        </FormItem>
                    </Form>
                </Card.Content>
                </Card>
            </Dialog>
        </div>
    );
}

export default UpdateUser;
